//@author A0101119Y
#include "GoogleRequestAgent.h"

using namespace Poco::Net;
using namespace Poco;
using namespace Twentyfifth;
using namespace std;

const string GoogleRequestAgent::METHOD_POST = "POST";
const string GoogleRequestAgent::METHOD_GET = "GET";
const string GoogleRequestAgent::METHOD_PUT = "PUT";
const string GoogleRequestAgent::METHOD_DELETE = "DELETE";
const string GoogleRequestAgent::METHOD_PATCH = "PATCH";


GoogleRequestAgent::GoogleRequestAgent() {
	responseCode = 0;
}

void GoogleRequestAgent::setURI(std::string uristring) {
	uri = URI(uristring);
	return;
}

string GoogleRequestAgent::getURI() {
	return uri.toString();
}

void GoogleRequestAgent::initSession() {
	string host = uri.getHost();
	httpsSession.setHost(host);
	httpsSession.setPort(443);
}

void GoogleRequestAgent::setRequestMethod(std::string method) {
	transform(method.begin(), method.end(), method.begin(), ::toupper);
	requestMethod = method;
}

string GoogleRequestAgent::getRequestMethod() {
	return requestMethod;
}

void GoogleRequestAgent::setRequestContent(std::string content) {
	requestContent = content;
}

string GoogleRequestAgent::getRequestContent() {
	return requestContent;
}

void GoogleRequestAgent::sendRequest() {
	string path = uri.getPathAndQuery();
	if (path.empty()) {
		path = "/";
	}
	request.setMethod(requestMethod);
	request.setURI(path);
	request.setContentLength(requestContent.length());
	httpsSession.sendRequest(request) << requestContent;
	responseReason = response.getReason();
	setResponseCode(response.getStatus());
	istream &is = httpsSession.receiveResponse(response);
	stringstream responseStream;
	StreamCopier::copyStream(is, responseStream);
	responseContent = responseStream.str();
	httpsSession.abort();
}

void GoogleRequestAgent::setResponseCode(HTTPResponse::HTTPStatus s) {
	responseCode = (int)s;
}

int GoogleRequestAgent::getResponseCode() {
	return responseCode;
}

void GoogleRequestAgent::setResponseContent(string s) {
	responseContent = s;
}

string GoogleRequestAgent::getResponseContent() {
	return responseContent;
}

void GoogleRequestAgent::setResponseReason(string s) {
	responseReason = s;
}

string GoogleRequestAgent::getResponseReason() {
	return responseReason;
}